<template>
  <view class="medical-tools-container">
    <!-- 顶部导航区 -->
    <view class="top-nav-bar">
      <view class="search-input-wrap">
        <text class="iconfont icon-search"></text>
        <input
          class="search-input"
          v-model="searchKeyword"
          placeholder="搜索工具名称或医学用途"
          @input="handleSearchInput"
          confirm-type="search"
        />
        <text class="clear-btn" v-if="searchKeyword" @tap="clearSearch">×</text>
      </view>
    </view>

    <!-- 分类导航区 -->
    <scroll-view class="category-nav-scroll" scroll-x :show-scrollbar="false">
      <view class="category-nav-wrap">
        <view
          :class="['category-tag', { 'active': currentCategory === 'all' }]"
          @tap="switchCategory('all')"
        >
          <view class="tag-icon" style="background-color: #F44336;">
            <text class="iconfont icon-medical-kit"></text>
          </view>
		  <text class="tag-name">全部</text>
        </view>
        <view
          v-for="(category, index) in categories"
          :key="index"
          :class="['category-tag', { 'active': currentCategory === category.name }]"
          @tap="switchCategory(category.name)"
        >
          <!-- 类别图标（目前只是占位符，可根据实际需求替换） -->
          <view class="tag-icon" :style="{ backgroundColor: category.color || '#4B7BFF' }">
            <text class="iconfont icon-category"></text> <!-- 示例图标 -->
          </view>
          <text class="tag-name">{{ category.name }}</text>
        </view>
        <!-- "常用工具"和"急救必备"作为额外分类标签 -->
        <view
          :class="['category-tag', { 'active': currentCategory === '常用工具' }]"
          @tap="switchCategory('常用工具')"
        >
          <view class="tag-icon" style="background-color: #FFC107;">
            <text class="iconfont icon-star"></text>
          </view>
          <text class="tag-name">常用工具</text>
        </view>
        <!-- <view
          :class="['category-tag', { 'active': currentCategory === '急救必备' }]"
          @tap="switchCategory('急救必备')"
        >
          <view class="tag-icon" style="background-color: #F44336;">
            <text class="iconfont icon-medical-kit"></text>
          </view>
          <text class="tag-name">急救必备</text>
        </view> -->
      </view>
    </scroll-view>

    <!-- 工具网格区 -->
    <view class="tools-grid-area">
      <view v-if="filteredTools.length > 0" class="tools-grid">
        <view
          class="tool-card"
          v-for="(tool, index) in filteredTools"
          :key="index"
          @tap="goToToolDetail(tool)"
        >
          <!-- 工具图标（根据类别或名称映射图标） -->
          <image :src="getToolIcon(tool)" class="tool-icon" mode="aspectFit"></image>
          <text class="tool-name">{{ tool.name }}</text>
          <text class="tool-description">{{ tool.medicalUse.split('、')[0] }}</text> <!-- 简短医学用途 -->
          <view class="detail-button">详情查看</view>
        </view>
      </view>
      <view v-else class="no-results">
        <text>暂无相关工具</text>
      </view>
    </view>
  </view>
</template>

<script>
import medicalToolsData from '@/utils/medicaltools.js';

export default {
  data() {
    return {
      searchKeyword: '',
      currentCategory: 'all', // 'all' 或具体的分类名称
      allMedicalTools: [], // 存储所有工具的扁平化列表
      filteredTools: [], // 显示在网格中的工具
      // 定义分类颜色映射，用于圆形图标
      categoryColors: {
        '诊断工具': '#4B7BFF',
        '外科器械': '#28A745',
        '家庭护理工具': '#FFC107',
        '急救工具': '#DC3545',
        '常用工具': '#FFC107', // 为特殊分类指定颜色
        '急救必备': '#DC3545', // 为特殊分类指定颜色
      },
    };
  },
  computed: {
    // 动态生成分类标签
    categories() {
      const uniqueCategories = new Set();
      medicalToolsData.forEach(cat => {
        uniqueCategories.add(cat.category);
      });
      return Array.from(uniqueCategories).map(name => ({
        name: name,
        color: this.categoryColors[name] || '#6C757D' // 默认颜色
      }));
    },
  },
  created() {
    // 将 medicalToolsData 扁平化，方便搜索和过滤
    this.allMedicalTools = medicalToolsData.flatMap(category =>
      category.tools.map(tool => ({ ...tool, category: category.category }))
    );
    this.filterTools(); // 初始化显示所有工具
  },
  methods: {
    handleSearchInput() {
      // 实时搜索
      this.filterTools();
    },
    clearSearch() {
      this.searchKeyword = '';
      this.filterTools();
    },
    switchCategory(categoryName) {
      this.currentCategory = categoryName;
      this.filterTools();
    },
    filterTools() {
      let tempTools = this.allMedicalTools;

      // 按分类过滤
      if (this.currentCategory !== 'all') {
        if (this.currentCategory === '常用工具') {
            // 示例：将诊断工具和家庭护理工具定义为常用工具
            tempTools = tempTools.filter(tool => 
                tool.category === '诊断工具' || tool.category === '家庭护理工具'
            );
        } else if (this.currentCategory === '急救必备') {
            // 示例：将急救工具定义为急救必备
            tempTools = tempTools.filter(tool => 
                tool.category === '急救工具'
            );
        } else {
            tempTools = tempTools.filter(tool => tool.category === this.currentCategory);
        }
      }

      // 按关键词搜索
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase();
        tempTools = tempTools.filter(tool =>
          (tool.name && tool.name.toLowerCase().includes(keyword)) ||
          (tool.medicalUse && tool.medicalUse.toLowerCase().includes(keyword))
        );
      }

      this.filteredTools = tempTools;
    },
    getToolIcon(tool) {
      // 根据工具名称返回对应的图片路径
      const toolNameImageMap = {
        '急救呼吸面罩': '/static/img/tools/急救呼吸面罩.png',
        '止血带': '/static/img/tools/止血带.png',
        'AED除颤仪': '/static/img/tools/AED除颤仪.png',
        '雾化器': '/static/img/tools/雾化器.png',
        '止血钳': '/static/img/tools/止血钳.png',
        '手术刀': '/static/img/tools/手术刀.png',
        '预充式注射器': '/static/img/tools/预充式注射器.png',
        '胰岛素笔': '/static/img/tools/胰岛素笔.png',
        '助行器': '/static/img/tools/助行器.png',
        '颈托': '/static/img/tools/颈托.png',
        '额温枪': '/static/img/tools/额温枪.png',
        '电子血压计': '/static/img/tools/电子血压计.png',
        '指夹式血氧仪': '/static/img/tools/指夹式血氧仪.png',
        '血糖仪': '/static/img/tools/血糖仪.png',
        '听诊器': '/static/img/tools/听诊器.png'
      };

      // 尝试获取具体工具的图片
      if (toolNameImageMap[tool.name]) {
        return toolNameImageMap[tool.name];
      }
      
      // 如果没有具体工具的图片，则回退到根据类别返回通用图标
      const categoryIconMap = {
        '诊断工具': '/static/images/icon-diagnosis.png',
        '外科器械': '/static/images/icon-surgery.png',
        '家庭护理工具': '/static/images/icon-homecare.png',
        '急救工具': '/static/images/icon-firstaid-kit.png',
        // 更多图标...
      };
      return categoryIconMap[tool.category] || '/static/images/icon-default.png'; // 默认图标
    },
    goToToolDetail(tool) {
      // 跳转到工具详情页，并传递工具数据
      uni.navigateTo({
        url: `/pages/guide/utils`, // 详情页路径
        success: (res) => {
          // 通过事件通道传递数据，避免URL参数过长
          res.eventChannel.emit('toolDetailData', tool);
        },
        fail: (err) => {
          console.error('跳转工具详情失败:', err);
          uni.showToast({ title: '跳转失败', icon: 'none' });
        }
      });
    },
  },
};
</script>

<style scoped>
.medical-tools-container {
  padding: 0 30rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 顶部导航区 */
.top-nav-bar {
  background-color: #fff;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
  position: sticky;
  top: 0;
  z-index: 10;
}

.search-input-wrap {
  display: flex;
  align-items: center;
  height: 72rpx;
  background-color: #F5F6FA;
  border-radius: 36rpx;
  padding: 0 30rpx;
}

.search-input-wrap .iconfont {
  font-size: 32rpx;
  color: #999;
  margin-right: 16rpx;
}

.search-input {
  flex: 1;
  height: 72rpx;
  font-size: 28rpx;
  color: #333;
}

.clear-btn {
  font-size: 40rpx;
  color: #999;
  padding-left: 20rpx;
}

/* 分类导航区 */
.category-nav-scroll {
  white-space: nowrap;
  padding: 20rpx 0;
  margin-top: 20rpx;
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 15rpx rgba(0,0,0,0.05);
}

.category-nav-wrap {
  display: flex;
  padding: 0 10rpx;
}

.category-tag {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  margin-right: 30rpx;
  padding: 10rpx 0;
  transition: transform 0.2s;
  flex-shrink: 0; /* 防止标签被压缩 */
}

.category-tag:active {
  transform: translateY(2rpx);
}

.tag-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10rpx;
  font-size: 40rpx;
  color: #fff;
}

.tag-icon .iconfont {
  font-size: 40rpx;
  color: #fff;
}

.tag-name {
  font-size: 26rpx;
  color: #666;
  text-align: center;
  line-height: 1.2;
}

.category-tag.active .tag-name {
  color: #4B7BFF;
  font-weight: bold;
}

/* 工具网格区 */
.tools-grid-area {
  padding: 30rpx 0;
}

.tools-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 3列布局 */
  gap: 20rpx; /* 网格间距 */
}

.tool-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx 10rpx;
  box-shadow: 0 4rpx 15rpx rgba(0,0,0,0.05);
  transition: transform 0.2s;
  text-align: center;
}

.tool-card:active {
  transform: translateY(2rpx);
}

.tool-icon {
  width: 100rpx;
  height: 100rpx;
  margin-bottom: 15rpx;
}

.tool-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1; /* 限制一行 */
  overflow: hidden;
}

.tool-description {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 15rpx;
  height: 60rpx; /* 固定高度，避免内容溢出 */
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2; /* 限制两行 */
  overflow: hidden;
  line-height: 1.4;
}

.detail-button {
  background-color: #0081FF;
  color: #fff;
  font-size: 24rpx;
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
  margin-top: auto; /* 按钮固定底部 */
  align-self: center;
}

.no-results {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
  font-size: 28rpx;
}

/* 常用和急救图标，可以在iconfont中查找类似图标 */
/* iconfont icon-search, icon-category, icon-star, icon-medical-kit */
</style> 